import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

export interface DictionaryItem {
  id: string;
  key: string;
  value: string;
  category: string;
  description?: string;
  sortOrder: number;
  enabled: boolean;
  createdAt: string;
  updatedAt: string;
}

@Injectable()
export class DictionaryService {
  private readonly dictionaryFile = path.join(process.cwd(), 'data', 'dictionary.json');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.dictionaryFile)) {
      fs.writeFileSync(this.dictionaryFile, JSON.stringify([]));
    }
  }

  private readDictionary(): DictionaryItem[] {
    const data = fs.readFileSync(this.dictionaryFile, 'utf8');
    return JSON.parse(data);
  }

  private writeDictionary(dictionary: DictionaryItem[]): void {
    fs.writeFileSync(this.dictionaryFile, JSON.stringify(dictionary, null, 2));
  }

  findAll(): DictionaryItem[] {
    return this.readDictionary();
  }

  findByCategory(category: string): DictionaryItem[] {
    const dictionary = this.readDictionary();
    return dictionary.filter(item => item.category === category && item.enabled);
  }

  findByKey(key: string): DictionaryItem | undefined {
    const dictionary = this.readDictionary();
    return dictionary.find(item => item.key === key && item.enabled);
  }

  findById(id: string): DictionaryItem | undefined {
    const dictionary = this.readDictionary();
    return dictionary.find(item => item.id === id);
  }

  create(dictData: Omit<DictionaryItem, 'id' | 'createdAt' | 'updatedAt'>): DictionaryItem {
    const dictionary = this.readDictionary();
    const newItem: DictionaryItem = {
      id: Date.now().toString(),
      ...dictData,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    dictionary.push(newItem);
    this.writeDictionary(dictionary);
    return newItem;
  }

  update(id: string, dictData: Partial<Omit<DictionaryItem, 'id' | 'createdAt'>>): DictionaryItem | null {
    const dictionary = this.readDictionary();
    const index = dictionary.findIndex(item => item.id === id);
    if (index === -1) return null;
    
    dictionary[index] = {
      ...dictionary[index],
      ...dictData,
      updatedAt: new Date().toISOString(),
    };
    
    this.writeDictionary(dictionary);
    return dictionary[index];
  }

  delete(id: string): boolean {
    const dictionary = this.readDictionary();
    const initialLength = dictionary.length;
    const filteredDictionary = dictionary.filter(item => item.id !== id);
    this.writeDictionary(filteredDictionary);
    return filteredDictionary.length !== initialLength;
  }
}